package com.elite.groovy.callback

import cn.com.tpUtil.GetXMLValue
import cn.com.tpUtil.SendPost
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat
//import org.json.JSONObject;
//import org.json.JSONArray;
//import org.json.JSONException;

public class JobXB_SMSTask implements ServiceBackInvoke{
private static final Log log =LogFactory.getLog(JobXB_SMSTask.class);
	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
	//调用存储过程处理工单
	log.debug("JobXB_SMSTask调用存储过程处理待调用接口任务数据...");
	String charset = "utf-8"; //设置字符集
	int timeout = 100000; //设置请求超时时间
	int enableSSLflag = 0;
	def IN_TOKEN ="";
	try {
		String selectSQL1="select INITCAP(Token_Type)||' '||Access_Token as token from Get_Token";
		def token1=eliteBean.chaxun_sql(selectSQL1, "dataSource");
		def queryMap1=token1[0];
		IN_TOKEN = queryMap1.get("token");
		log.debug("请求短信校验接口token获取:" + IN_TOKEN);
	}catch (Exception e) {
		IN_TOKEN ="NULL";
		log.debug("请求短信校验接口token获取:" + IN_TOKEN);
	};
	String selectSQL2="select F_Get_Token('"+IN_TOKEN+"') as outstring from dual";
	def outstring1=eliteBean.chaxun_sql(selectSQL2, "dataSource");
	def queryMap2=outstring1[0];
	def IN_OUT = queryMap2.get("outstring");
	log.debug("请求短信校验接口token是否过期:" + IN_OUT);
	String ProcExecute = "";
	String PostNo = "";// 调用地址URL
	String PostURL = "";// 调用地址URL
	String PostXml = "";// 接口调用报文
	String CheckURL = "";// 检查调用地址URL
	String CheckXml = "";// 检查调用报文XML
	String Max_OEND_DATE = "";// 当前保单号后的保险止期、
	String VAR_QTID = "";//是否新旧单 DNTS新单 否则为旧单
	def Re = "";
	def Request_Type ="";
	def Response_Code ="";
	def Error_Message = "";
	if(IN_OUT=="FAIL"){
		log.debug("-------------发送调用token获取接口------------------");
		String selectSQL3="select WEBSERVICEURL from sysc_interface where webtype='PTJKTOKEN'";
		def postURL=eliteBean.chaxun_sql(selectSQL3, "dataSource");
		def httpURL=postURL[0].get("WEBSERVICEURL");
		log.debug("短信token获取接口地址:"+httpURL);
		Map headMap=new HashMap(); //设置头文件
		headMap.put("Content-Type","application/json");
		Re = Util.doHttpPostUseHead(httpURL,PostXml,charset,timeout,enableSSLflag,headMap);
		JSONObject obj = JSONObject.fromObject(Re);
		log.debug("短信token获取接口返回报文obj:"+obj);
		String selectSQL4="select substr('"+obj+"',instr('"+obj+"','access_token')+13,instr('"+obj+"','token_type')-instr('"+obj+"','access_token')-15) as accesstoken from dual";
		def accesstoken1=eliteBean.chaxun_sql(selectSQL4, "dataSource");
		def accesstoken2=accesstoken1[0].get("accesstoken");
		log.debug("短信token获取接口地址accesstoken2:"+accesstoken2);
		def insertSQL1=" delete from Get_Token";
		int num1=eliteBean.update(insertSQL1,"dataSource");
		def insertSQL2="insert into Get_Token(Access_Token,Token_Type,Createddate,Expirddate,Responsedjson) values ('"+accesstoken2+"','Bearer',sysdate,sysdate+1/25 ,'"+obj+"')";
		int num2=eliteBean.update(insertSQL2,"dataSource");
		IN_TOKEN=accesstoken2;
		log.debug("token过期后重新调用接口获取新的token:"+IN_TOKEN);
		}
	// 设置日期格式
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	// new Date()为获取当前系统时间
	ProcExecute = df.format(new Date());
	
	log.debug("获取当前时间:" + ProcExecute);
	def procedure = "{call Auto_Get_Info(?,?,?,?,?,?,?,?)}";
	String inputMap="[{\"mode\":\"in\",\"type\":\"string\",\"value\":\""+ProcExecute+"\"},{\"mode\":\"out\",\"type\":\"string\",\"value\":\"\"},{\"mode\":\"out\",\"type\":\"string\",\"value\":\"\"},{\"mode\":\"out\",\"type\":\"string\",\"value\":\"\"},{\"mode\":\"out\",\"type\":\"string\",\"value\":\"\"},{\"mode\":\"out\",\"type\":\"string\",\"value\":\"\"},{\"mode\":\"out\",\"type\":\"string\",\"value\":\"\"},{\"mode\":\"out\",\"type\":\"string\",\"value\":\"\"}]";
    log.debug("JobXB_SMSTask调用存储过程处理返回:" + inputMap);
	List<String> list = new ArrayList<String>();
	list = eliteBean.executeWithMultiReturn(procedure,'dataSource',inputMap);
	log.debug("JobXB_SMSTask调用存储过程处理返回:" + list.toString());

	PostNo = list.get(0);
	PostURL = list.get(1);
	PostXml = list.get(2);
	CheckURL = list.get(3);
	CheckXml = list.get(4);
	Max_OEND_DATE = list.get(5);
	VAR_QTID = list.get(6);
	// 初始化调用验证结果，以下是调用SendPost
	boolean checkFlag = true;
	String checkRemark = "";

try{
	def succ="";
	def	CRequest_Type="";
	def CResponse_Code="";
	def CError_Message="";
	def JQ_POLICY_NO="";
	def JQ_SUB_POLICY_NO="";
	def JQ_START_DATE="";
	def JQ_END_DATE="";
	def	SY_POLICY_NO="";
	def SY_SUB_POLICY_NO="";
	def SY_START_DATE="";
	def SY_END_DATE="";
	if (PostNo != null && PostNo.length() > 0) {
		if(CheckXml == null || CheckXml.length() <= 0) {
		log.debug("发送前无需要校验信息...");
		}else {
			//解析返回Json内容
					log.debug("---------------打印调用续保短信校验接口结果---------------")	
				//判断是否新接口
				if(VAR_QTID=='DNTS'){
					log.debug("开始调用续保短信校验接口CheckURL:"+ CheckURL+"  CheckXml:"+ CheckXml+"是否新接口1"+VAR_QTID);
					log.debug("PostNo:"+PostNo);
					Map headMap1=new HashMap(); //设置头文件
					headMap1.put("Content-Type","application/json");
					headMap1.put("Authorization",IN_TOKEN);
								Re = Util.doHttpPostUseHead(CheckURL,CheckXml,charset,timeout,enableSSLflag,headMap1);							 

								JSONObject obj = JSONObject.fromObject(Re);
								log.debug("转JSON对象打印调用续保短信校验接口结果:"+Re);
								
								succ=obj.get("succ");
								log.debug("成功标识，请求失败会返回false:"+succ);
								
								if(obj.get("errType")==''||obj.get("errType")==null)
								{
									CRequest_Type ='无';
								}	
								else{
									CRequest_Type=obj.get("errType");
									
								}
									CResponse_Code=obj.get("errCode");
									
									CError_Message=obj.get("errMsg");
									
									obj= obj.get("data");
									JQ_POLICY_NO=obj.get("jq_policy_no");
									log.debug("交强险保单号:"+JQ_POLICY_NO);
									JQ_SUB_POLICY_NO=obj.get("jq_policy_no");
									log.debug("交强险保单号:"+JQ_SUB_POLICY_NO);
									JQ_START_DATE=obj.get("jq_start_date");
									log.debug("交强险保险起期:"+JQ_START_DATE);
									JQ_END_DATE=obj.get("jq_end_date");
									log.debug("交强险保险止期:"+JQ_END_DATE);
									SY_POLICY_NO=obj.get("sy_policy_no");
									log.debug("商业险保单号:"+SY_POLICY_NO);
									SY_SUB_POLICY_NO=obj.get("sy_policy_no");
									log.debug("商业险保单号:"+SY_SUB_POLICY_NO);
									SY_START_DATE=obj.get("sy_start_date");
									log.debug("商业险保险起期:"+SY_START_DATE);			
									SY_END_DATE=obj.get("sy_end_date");
									log.debug("交强险保险止期:"+SY_END_DATE);
							
				}
				else{
					 log.debug("开始调用续保短信校验接口CheckURL:"+ CheckURL+"  CheckXml:"+ CheckXml+"是否新接口2"+VAR_QTID);
					 SendPost checksend = new SendPost();
					 Re = Util.doHttpPost(CheckURL, CheckXml, "UTF-8",120000, 0);
					 log.debug("调用续保短信校验接口结果:"+Re);
					 CRequest_Type = GetXMLValue.main(Re, "REQUEST_TYPE");
					 CResponse_Code = GetXMLValue.main(Re, "RESPONSE_CODE");
					 CError_Message = GetXMLValue.main(Re, "ERROR_MESSAGE");
					 JQ_POLICY_NO = GetXMLValue.main(Re, "JQ_POLICY_NO");
					 JQ_SUB_POLICY_NO = GetXMLValue.main(Re, "JQ_SUB_POLICY_NO");
					 JQ_START_DATE = GetXMLValue.main(Re, "JQ_START_DATE");
					 JQ_END_DATE = GetXMLValue.main(Re, "JQ_END_DATE");
					 SY_POLICY_NO = GetXMLValue.main(Re, "SY_POLICY_NO");
					 SY_SUB_POLICY_NO = GetXMLValue.main(Re, "SY_SUB_POLICY_NO");
					 SY_START_DATE = GetXMLValue.main(Re, "SY_START_DATE");
					 SY_END_DATE = GetXMLValue.main(Re, "SY_END_DATE");
					
				}
			def insertSQL = "insert into Autoinvokinginfo_EXTEND (INVOKING_NO, REQUEST_TYPE, RESPONSE_CODE, ERROR_MESSAGE, JQ_POLICY_NO, JQ_SUB_POLICY_NO, JQ_START_DATE, JQ_END_DATE, SY_POLICY_NO, SY_SUB_POLICY_NO, SY_START_DATE, SY_END_DATE, CREATEDTIME, RESULT_INFO) values('"+PostNo+"', '"+CRequest_Type+"', '"+CResponse_Code+"', '"+CError_Message+"', '"+JQ_POLICY_NO+"', '"+JQ_SUB_POLICY_NO+"', '"+JQ_START_DATE+"', '"+JQ_END_DATE+"', '"+SY_POLICY_NO+"', '"+SY_SUB_POLICY_NO+"', '"+SY_START_DATE+"', '"+SY_END_DATE+"', Sysdate, '"+Re+"')";
			log.debug("处理续保短信校验接口结果SQL:" + insertSQL);
			eliteBean.update(insertSQL, 'dataSource');

			// 开始判断是否不再需要发送短信
			/*
			 * 规则： 1.通过返回的险种的保险起期进行判断，返回的保险起期和上一年保单的止期进行比较，起期大于止期则不发送短信
			 * 2.如果返回的险种只有一个，例如只有交强险，那么继续发送短信
			 */
			String Min_START_DATE = "";
			if (JQ_POLICY_NO != null && JQ_POLICY_NO.length() > 0 && SY_POLICY_NO != null && SY_POLICY_NO.length() > 0) {

				//比较两个时间的大小
				int res1 = JQ_START_DATE.compareTo(SY_START_DATE);

				if (res1 < 0) {
					//如果交强险小，则将交强起保时间当最早时间
					Min_START_DATE = JQ_START_DATE;
				} else {
					//如果商业险小，则将商业起保时间当最早时间
					Min_START_DATE = SY_START_DATE;
				}

				log.debug("当前核心返回保单起保时间最小为:" + Min_START_DATE);

				// 返回的保险起期和上一年保单的止期进行比较，起期大于止期则不发送短信
				int res2 = Min_START_DATE.compareTo(Max_OEND_DATE);
				if (res2 > 0) {
					log.debug("该客户已在我司其他渠道承保综合险！");
					checkFlag = false;
					checkRemark = "该客户已在我司其他渠道承保综合险！";
				} else {
					log.debug("起期不大于止期则发送短信");
					checkFlag = true;
				}

			} 
			
			else {
				log.debug("如果返回的险种只有一个，例如只有交强险，那么继续发送短信(根据返回的保单号数量检查判断)");
				checkFlag = true;
			}

		}

			//通过检查车架号检查续保状态后如果需要发送短信继续执行发送信息
			Re="";
			Request_Type ="";
			Response_Code ="";
			Error_Message = "";
			if(checkFlag) {
				log.debug("---------------打印发送调用核心返回信息---------------")				
				if(VAR_QTID=='DNTS'){	
						    log.debug("发送调用核心返回信息...是否新接口:"+ PostURL+"  CheckXml:"+ PostXml+"是否新接口1"+VAR_QTID);
							Map headMap2=new HashMap(); //设置头文件
							headMap2.put("Content-Type","application/json");
							headMap2.put("Authorization",IN_TOKEN);
							Re = Util.doHttpPostUseHead(PostURL,PostXml,charset,timeout,enableSSLflag,headMap2);
							JSONObject obj = JSONObject.fromObject(Re);
								 Request_Type=obj.get("success");
								 Response_Code=obj.get("code");
								 Error_Message=obj.get("msg");
								log.debug("返回错误信息描述:"+Error_Message);
								
				}else{
					log.debug("发送调用核心返回信息...是否新接口"+VAR_QTID);
					Re = Util.doHttpPost(PostURL, PostXml, "UTF-8",120000, 0);
		
					Request_Type = GetXMLValue.main(Re, "REQUEST_TYPE");
					Response_Code = GetXMLValue.main(Re, "RESPONSE_CODE");
					Error_Message = GetXMLValue.main(Re, "ERROR_MESSAGE");
					log.debug("返回错误信息描述:"+Error_Message);
				}
		}else {
					log.debug("检查失败回写任务主表...");
					Re = checkRemark;
					Request_Type = "";
					Response_Code = "";
					Error_Message = "";

		}
		log.debug("调用结果回写任务主表...")
		String ProcEndTime = df.format(new Date());
		def updateSQL="DECLARE  clobValue Autoinvokinginfo.Result_Info%TYPE;  BEGIN  clobValue:='" + Re + "' ;Update Autoinvokinginfo R2 Set R2.Invoking_Flag = '1',R2.Result_Info=clobValue,R2.End_Time= To_Date('"+ProcEndTime+"','yyyy-mm-dd hh24:mi:ss'),Request_Type='"+Request_Type+"',Response_Code='"+Response_Code+"',Error_Message='"+Error_Message+"' Where R2.Invoking_No = '"+PostNo+"';   COMMIT; END;";
		eliteBean.update(updateSQL, 'dataSource');
		log.debug("调用结果回写任务主表SQL:" + updateSQL);
		log.debug("电销处理成功！");
	}else {
		log.debug("PostNo（调用任务编号）为空不需要调用Stop SendPost...");
	}
	
}
catch(Exception e){
		log.debug(e);
	}
}
	
	
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		return Rev_Value;
	}
}